<template>
  <div class="m-iselect">
    <span class="name">按省份选择</span>
    <el-select v-model="pvalue" placeholder="请选择">
    <el-option
      v-for="item in province"
      :key="item.id"
      :label="item.name"
      :value="item.id">
    </el-option>
  </el-select>

    <el-select v-model="cvalue" placeholder="请选择" :disabled="!city.length">
      <el-option
      v-for="item in city"
      :key="item.id"
      :label="item.name"
      :value="item.id">
      </el-option>
    </el-select>

    <span class="search-name">直接搜索：</span>
    <el-autocomplete
      v-model="input"
      :fetch-suggestions="querySearchAsync"
      placeholder="请输入城市中文名或拼音"
      :trigger-on-focus="false"
      @select="handleSelect"
    ></el-autocomplete>
  </div>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
  data() {
    return {
      province: [],
      city: [],
      pvalue:'',
      cvalue: '',
      input:'',
      allCity: []
    }
  },
  async mounted() {
    let {status, data} = await this.$store.dispatch('api/getProvince')
    if (status === 200 && data.code === 0) {
      this.province = data.province
    }
  },
  methods: {
    async querySearchAsync(query, cd) {
      let self = this;
      
      if (this.allCity.length) {
        cd(this.allCity.filter(item => {return item.value.indexOf(query) > -1}))
      } else {
        let {status, data} = await this.$store.dispatch('api/getAllCitys')
        if (status === 200 && data.code === 0) {
          this.allCity = data.city.map(item => {return {value: item.name, province: item.province}})
          cd(this.allCity.filter(item => {
            return item.value.indexOf(query) > -1
          }))
        } else {
          cd([])
        }
      }
    },
    async handleSelect(item) {
      this.$store.commit('api/SET_POSITION', {city: item.value, province: item.province})
      location.href = '/'
    }
  },
  watch: {
    async pvalue(newPvalue) {
      let {status, data} = await this.$store.dispatch('api/getCitys', newPvalue)
      if (status === 200 && data.code === 0) {
        this.city = data.city
        this.cvalue = ''
      }
    }
  }
}
</script>
<style lang="scss">
@import "@/assets/css/changecity/iselect.scss";
</style>
